
var startObject = document.getElementById('start');
var LocalStream = document.getElementById('LocalRtcStream')
// rtc object

var localPeer  = new RTCPeerConnection(null);

var containers = {

    video: true,
    audio: true,
}

var pushServer = "http://172.17.0.2:1985/rtc/v1/publish/";
var playServer = "http://172.17.0.2:1985/rtc/v1/play/";

var remote_server = "https://180.76.187.29:1900/rtc/v1/publish/"

// type: "POST", url: conf.apiUrl, data: JSON.stringify(data),
startObject.onclick = function() {
    // get user media
    var containers = {
        audio: true,
        // video: true,
        video: {
            width: 320,
            height: 360,
        },
    }
    navigator.getUserMedia(containers, function(result) {
        
        $('#LocalRtcStream').show();
        $('#LocalRtcStream').prop('srcObject', result);

        localPeer.addStream(result)

        var optional =  {

            offerToReceiveAudio: 1,
            offerToReceiveVideo: 1,
        };
        // localPeer.addTransceiver("audio", {direction: "sendonly"});
        // localPeer.addTransceiver("video", {direction: "sendonly"});

        localPeer.addEventListener("connectionstatechange", connectedStateChanged)

        localPeer.addIceCandidate(function(event){

            if (event.candidate == null) {

                return;
            }
            console.log(event.candidate.candidate);
        });
        localPeer.createOffer(optional).then((result) => {

            CreateOffer(result);

        }).catch((err) => {});;

    },function(err) {
        
    });
}

var hasSubscribe = false

function CreateOffer(session) {

    localPeer.setLocalDescription(session);

    console.log("created offer : ", session.type)
    req = new XMLHttpRequest()
    var data = {
        api:pushServer,
        clientip:null,
        streamurl: "webrtc://172.17.0.2/live/" + "121212",
        sdp: session.sdp,
        tid: Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).substring(0,7),
    }
    req.open('POST', pushServer, true);

    req.onload = function(response) {

        message = JSON.parse(response.currentTarget.response);
        console.log(message.sdp)
        localPeer.setRemoteDescription(
            {type: 'answer', sdp: message.sdp}
        );
    }
    binaryData = JSON.stringify(data),
    req.send(binaryData);
}


var playUrl = "http://172.17.0.2:1985/rtc/v1/play/"

function connectedStateChanged(event) {

    console.log("connectedStateChanged")
    if (hasSubscribe == true) {
        return;
    }
    hasSubscribe = true

    local = new RTCPeerConnection(null);
    var optional =  {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
    };
    
    local.addEventListener('addstream', gotRemoteMediaStream);
    local.createOffer(optional).then((result) => {

        local.setLocalDescription(result);
        var dataMsg = {
            api: playServer,
            clientip: null,
            sdp: result.sdp,
            streamurl: "webrtc://172.17.0.2/live/" + "121212",
            tid: Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).substring(0,7),
        }
        console.log("debug")
        palyReq = new XMLHttpRequest()

        palyReq.open('POST', playServer, true);

        palyReq.onload = function(response) {
    
            message = JSON.parse(response.currentTarget.response);
            console.log(message.sdp)
            local.setRemoteDescription(
                {type: 'answer', sdp: message.sdp}
            );
        }
        binaryData = JSON.stringify(dataMsg),
        palyReq.send(binaryData);

    }).catch((err) => {});;
}

function HandleCreateOfferErr(msg) {

}

function gotRemoteMediaStream(event) {

    console.log(event)
    $('#playVideo').show();
    $('#playVideo').prop('srcObject', event.stream);

    PlayStream()
}


// ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

async function PlayStream(roomId) {

    var optional =  {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
    };
    play = new RTCPeerConnection(null);
    local.addEventListener('addstream', gotRemoteMediaStream);
    var offer = await local.createOffer();
    if (offer.type != 'offer') {

        console.log("the sdp type is not offer")
    }

}

